<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px">专业管理</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >开设院校管理</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="search">
      <el-form :inline="true" :model="infoForm" class="demo-form-inline">
        <el-form-item>
          <el-input
            style="width: 200px"
            placeholder="请输入专业名称"
            v-model="majorName"
            @blur="getUniList_Token"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            style="width: 200px"
            placeholder="请输入院校名称"
            v-model="collegeName"
            @blur="getUniList_Token"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="searchMajor"
            style="background-color: rgba(255, 101, 0); color: #fff"
            icon="el-icon-search"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-upload
            class="upload-demo"
            action="http://192.168.229.26:8318/back/importUScore"
            multiple
            :on-success="handleAvatarSuccess"
          >
            <el-button style="background-color: rgba(255, 101, 0); color: #fff"
              >批量导入</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="toggleSelection()" style="color: rgba(255, 101, 0)"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="multipleTable"
      :data="resultLists"
      v-loading="listLoading"
      border
      style="
        width: 1221px;
        margin-left:10px
        position: relative;
      "
      :header-cell-style="headClass"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="70"> </el-table-column>
      <el-table-column
        label="专业名称"
        width="350"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开设院校" width="350" align="center">
        <template slot-scope="scope">
          <div class="name_des">
            <div class="top_item">
              <span class="float_l set_hoverl am_l">
                <router-link
                  :to="`/college/${scope.row.unvId}`"
                  class="link_name clearfix"
                >
                  {{ scope.row.name }}
                </router-link>
                <!-- <el-tag
                  type="danger"
                  size="small"
                  v-if="scope.row.nationFeature === '1'"
                  >国家特色专业</el-tag
                > -->
              </span>
            </div>
            <div class="bottom_item">
              <span class="tag_item" v-text="infoForm.batch"></span>
              <span class="tag_item">{{ scope.row.type }}</span>
              <span class="tag_item">{{ scope.row.province }}</span>
              <span class="tag_item" style="border: none">{{
                scope.row.category
              }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否为该院校的国家特色专业" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.nationFeature === '1'">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      layout="total, prev, pager, next"
      :total="queryInfo.count"
      background
    >
      <!--
        @current-change(页码发生改变时触发)
        :current-page(设置当前页码)
        :page-size(设置每页的数据条数)
        :total(设置总页数)
     -->
    </el-pagination>
  </el-card>
</template>

<script>
import qs from "qs";
import throttling from "@/public/throttling.js";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("专业名称不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else {
          // console.log("输入合法");
          // console.log(typeof value);
          callback();
        }
      }
    };
    var validateCategory = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("专业层次不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else if (value.search("科") === -1) {
          callback(new Error("填写格式为xx科!"));
        } else {
          // console.log("输入合法");
          // console.log(typeof value);
          callback();
        }
      }
    };
    var validateType = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("专业门类不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else if (value.search("学") === -1) {
          callback(new Error("填写格式为xx学!"));
        } else {
          // console.log("输入合法");
          // console.log(typeof value);
          callback();
        }
      }
    };
    return {
      // 获得当前年份
      nowDate: new Date(),
      // 选择
      // 信息选择
      infoForm: {
        batch: "",
        type: "",
      },
      batchList: [
        {
          value: "本科一批",
        },
        {
          value: "本科二批",
        },
        {
          value: "高职专科批",
        },
      ],
      typeList: [
        {
          value: "理科",
        },
        {
          value: "文科",
        },
      ],
      // 正确性验证
      nameIsRight: 0,
      nameMsg: "",
      // 搜索
      collegeName: "",
      majorName: "",
      // 按钮
      showEdit: true,
      showRemove: true,
      listLoading: false,
      // 控制修改院校
      editDialogVisible: false,
      // 修改用户的表单数据
      editForm: {
        fname: "",
        name: "",
        category: "",
        type: "",
      },
      // 属性
      editFormRules: {
        name: [{ validator: validateName, trigger: "blur" }],
        // 专业层次
        category: [{ validator: validateCategory, trigger: "blur" }],
        // 专业门类
        type: [{ validator: validateType, trigger: "blur" }],
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 6,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      resultLists: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 表格表头
    headClass() {
      //表头居中显示
      return "color:rgba(0,0,0,.8);font-weight:bold;font-size:16px;text-align:center";
    },
    // 文件上传成功
    handleAvatarSuccess() {},
    // 批量删除
    toggleSelection(rows) {
      let collegeAndMajorList = [];
      let list = [];
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        console.log(this.multipleSelection);
        this.multipleSelection.forEach((row) => {
          for (let i = 0; i < list.length; i++) {
            if (list[i].unvId === row.unvId) {
              list[i].majorList.push(row.majorId);
            }
            return;
          }

          list.push({
            unvId: row.unvId,
            majorList: [row.majorId],
          });
        });
        console.log(list);
        this.$axios
          .delete("/back/universityScore", {
            data: {
              year: this.majorLineList.year,
              batch: this.majorLineList.batch,
              type: this.majorLineList.type,
              list: list,
            },
          })
          .then((res) => {
            this.getUniList_Token();
          });
      }
    },
    // 多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange: throttling(function (page) {
      this.queryInfo.pagenum = page;
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      this.getUniList_Token();
    }, 1000),
    cancel() {
      this.editDialogVisible = false;
      this.$message("取消修改");
    },
    getUniList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios
        .get("/back/majors", {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.status === 666) {
            this.$message.error("请先登录");
            this.$router.replace("/login");
          } else {
            this.$message.success("获取推荐专业列表成功！");
            this.resultLists = res.data.data;
            this.queryInfo.count = res.data.code;
          }
        });
    },
    showEditDialog(name) {
      //   //将获取到的数据保存到数据editForm中
      this.editForm.fname = name;
      //显示弹出窗
      this.editDialogVisible = true;
      // });
    },
    editDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.editFormRef.resetFields();
    },
    editUser: throttling(function () {
      // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        else {
          const token = window.sessionStorage.getItem("tokenvalue");
          this.$axios.defaults.headers.common["satoken"] = token;
          // 发送请求 完成修改用户的操作
          this.$axios
            .put(
              "/back/major",
              qs.stringify({
                fName: this.editForm.fname,
                name: this.editForm.name,
                category: this.editForm.category,
                type: this.editForm.type,
              })
            )
            .then((res) => {
              //修改成功的提示
              this.$message.success("修改专业成功");
              //关闭对话框
              this.editDialogVisible = false;
              //重新请求最新的数据
              this.getUniList_Token();
            });
        }
      });
    }, 1000),
    removeUserById(name) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久删除该专业", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
      })
        .then(() => {
          //发送请求根据id完成删除操作
          this.$axios;
          this.$axios.delete("/back/major/" + name).then((res) => {
            //修改成功的提示
            this.$message.success("删除专业成功");
            //重新请求最新的数据
            this.getUniList_Token();
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消删除" : "放弃删除",
          });
        });
    },
    searchMajor: throttling(function () {
      this.$axios
        .get("/back/major/" + this.majorName, {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          this.resultLists = res.data.data;
          this.queryInfo.count = res.data.code;
        });
    }, 1000),
  },
  created() {
    this.infoForm.batch = this.batchList[0].value;
    this.infoForm.type = this.typeList[0].value;

    this.$axios.get("/back/major/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showEdit = false;
      }
    });
    this.$axios.get("/back/major/deleteButton").then((res) => {
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
    this.getUniList_Token();
  },
};
</script>

<style scoped>
.box-card {
  position: relative;
  margin: 22px auto;
  min-height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.search {
  margin-top: 20px;
  margin-left: 5px;
}

.el-table {
  margin-top: 20px;
}

.el-dialog .el-dialog__body {
  padding: 10px 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.pagination {
  position: absolute;
  bottom: 10px;
  width: 412px;
  left: 50%;
  margin-left: -206px;
}
</style>